const Base = require('./base.js');
const path = require('path');
module.exports = class extends Base {

	constructor(ctx) {
		super(ctx);
		
		this.wxuser = this.model("weixin/user");
		this.conf = this.model("weixin/config");
		this.order = this.model("taoke/order");
		this.qrcode = this.model("taoke/qrcode");
		this.queue = this.model("taoke/queue");
		this.user = this.model("system/user");
		this.log = this.model("system/log");
		this.smslog = this.model("system/smslog");
		this.asset = this.model("system/asset");
		this.score = this.model("system/score");
		this.money = this.model("system/money");
		this.agency = this.model("system/agency");
		this.message = this.model("system/message");
		this.appid = think.config('setup.weixinAppid');

	}

	async loginAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {

			let posts = this.post();
			let openid = await this.session("weixinOpenid");
			let username = posts.username;
			let password = posts.password;
			let wxuser = await this.wxuser.where({
				openid: openid
			}).find();
			if(!think.isEmpty(wxuser.user_id)) {
				return this.fail("该微信已绑定会员");
			}

			if(!username || !password) {
				return this.fail("用户名密码不能为空");
			}
			let user = await this.user.where({
				username: username
			}).find();

			if(think.isEmpty(user)) {
				return this.fail("用户名不存在");
			}

			if(user.status == 0) {
				return this.fail("用户被禁用");
			}
			if(user.password != this.password(password, user.username, user.create_time)) {
				return this.fail("密码不正确");
			}
			let create_time = new Date().valueOf();
			await this.wxuser.transaction(async() => {
				let asset = await this.asset.db(this.wxuser.db()).where({
					user_id: user.id
				}).find();

				if(think.isEmpty(asset)) {
					await this.asset.db(this.wxuser.db()).add({
						score: 0,
						amount: 0,
						rebate: 0,
						team_count: 0,
						user_id: user.id,
						agency_id: wxuser.agency_id,
						create_time: create_time
					});
				}

				let agency = await this.agency.db(this.wxuser.db()).where({
					user_id: user.id
				}).find();

				if(think.isEmpty(agency)) {
					await this.agency.db(this.wxuser.db()).add({
						level: 1,
						status: 1,
						user_id: user.id,
						create_time: create_time,
					});
				}
				if(!think.isEmpty(wxuser.agency_id)) {
					let agencyUserId = await this.agency.db(this.wxuser.db()).where({
						id: wxuser.agency_id
					}).getField("user_id", true);
					await this.asset.db(this.wxuser.db()).where({
						user_id: agencyUserId
					}).increment("team_count");
				}

				await this.user.db(this.wxuser.db()).setOne(user.id, {
					online: 1,
					last_login_ip: this.ip,
					last_login_time: create_time,
					login_count: user.login_count++
				});

				await this.log.db(this.wxuser.db()).add({
					type: 'wemp',
					url: this.ctx.url,
					note: "登录成功",
					user_id: user.id,
					create_nickname: user.nickname,
					create_ip: this.ip,
					create_time: create_time
				});

				return await this.wxuser.where({
					openid: wxuser.openid
				}).update({
					user_id: user.id
				});
			});

			let userInfo = await this.wxuser.where({
				openid: openid
			}).find();
			await this.session("user", userInfo);
			return this.success("绑定会员成功");
		}

	}

	async getcodeAction() {

		if(!this.isPost) {
			return this.fail('请求错误！');
		}

		const posts = this.post();
		const code = this.mathRand();

		const user = await this.user.where({
			mobile: posts.mobile
		}).find();
		if(posts.type == 1) { //注册验证账号是否存在

			if(!think.isEmpty(user)) {
				return this.fail('该手机号账户已存在！');
			}
		}

		if(posts.type == 2) { //验证账号已存在
			if(think.isEmpty(user)) {
				return this.fail('该手机号账户不存在！');
			}
		}
		// 检查执行周期
		const map = {
			mobile: posts.mobile,
			type: posts.type
		};
		map.create_time = ['>', new Date().valueOf() - 24 * 3600 * 1000];

		const exec_count = await this.smslog.where(map).count();

		if(exec_count >= 3) {
			return this.fail('发送过于频发请24小时后，再尝试。');
		}

		//		const dayu = this.extService('client');
		//		const qianming = this.config('ext.dayu.qianming');
		//		let temp_code;
		//		if(posts.type == 1) {
		//			temp_code = this.config('ext.dayu.zhuce');
		//		}
		//		const info = {
		//			'extend': posts.mobile,
		//			'sms_type': 'normal',
		//			'sms_free_sign_name': qianming,
		//			'sms_param': `{"code":"${code}","product":"${this.config('ext.dayu.product')}"}`,
		//			'rec_num': posts.mobile,
		//			'sms_template_code': temp_code
		//		};
		//		const result = await dayu.send(info);

		let result = {
			err_code: '0',
			model: '102201717069',
			success: true,
			code: code
		}

		console.log(result);
		// 发送成功记录到数据库
		if(result.err_code == 0) {
			await this.smslog.add({
				mobile: posts.mobile,
				type: posts.type,
				code: code,
				create_time: new Date().valueOf()
			});
		}
		return this.success(result);
	}

	async forgetAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			const posts = this.post();
			// 对比验证码
			const map = {
				mobile: posts.mobile,
				type: posts.type
			};
			map.create_time = ['>', new Date().valueOf() - 1 * 3600 * 1000];
			const code = await this.smslog.where(map).order('id DESC').getField('code', true);
			if(think.isEmpty(code) || code != posts.verifyCode) {
				return this.fail('验证码不正确!');
			}
			const pattern = /^(\w){6,20}$/;
			if(!pattern.test(posts.password)) {
				return this.fail('密码只能输入6-20个字母或数字组合');
			}

			let user = await this.user.where({
				mobile: posts.mobile
			}).find();

			if(think.isEmpty(user)) {
				return this.fail('该手机号未注册!');
			}

			const reg = await this.user.where({
				mobile: posts.mobile
			}).update({
				password: this.password(posts.password, user.username, user.create_time)
			});

			return this.success();
		}

	}

	async registerAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			const posts = this.post();

			// 对比验证码
			const map = {
				mobile: posts.mobile,
				type: posts.type
			};
			map.create_time = ['>', new Date().valueOf() - 1 * 3600 * 1000];

			const code = await this.smslog.where(map).order('id DESC').getField('code', true);
			if(think.isEmpty(code) || code != posts.verifyCode) {
				return this.fail('验证码不正确!');
			}
			const pattern = /^(\w){6,20}$/;
			if(!pattern.test(posts.password)) {
				return this.fail('密码只能输入6-20个字母或数字组合');
			}

			let username = await this.user.where({
				username: posts.username
			}).find();

			let mobile = await this.user.where({
				mobile: posts.mobile
			}).find();

			if(!think.isEmpty(username)) {
				return this.fail('用户名已被使用');
			}

			if(!think.isEmpty(mobile)) {
				return this.fail('手机号已存在');
			}

			let create_time = new Date().valueOf();
			let openid = await this.session("weixinOpenid");

			let user = await this.wxuser.where({
				openid: openid
			}).find();

			await this.wxuser.transaction(async() => {

				const userid = await this.user.db(this.wxuser.db()).add({
					username: posts.username,
					mobile: posts.mobile,
					status: 1,
					create_time: create_time,
					password: this.password(posts.password, posts.username, create_time),
					nickname: user.nickname
				});

				await this.asset.db(this.wxuser.db()).add({
					score: 0,
					amount: 0,
					rebate: 0,
					team_count: 0,
					user_id: userid,
					agency_id: user.agency_id,
					create_time: create_time,
				});
				if(!think.isEmpty(user.agency_id)) {
					let agencyUserId = await this.agency.db(this.wxuser.db()).where({
						id: user.agency_id
					}).getField("user_id", true);
					await this.asset.db(this.wxuser.db()).where({
						user_id: agencyUserId
					}).increment("team_count");
				}
				await this.agency.db(this.wxuser.db()).add({
					level: 1,
					status: 1,
					user_id: userid,
					create_time: create_time,
				});

				await this.user.db(this.wxuser.db()).setOne(userid, {
					online: 1,
					last_login_ip: this.ip,
					last_login_time: create_time,
					login_count: 1
				});

				await this.log.db(this.wxuser.db()).add({
					type: 'wemp',
					url: this.ctx.url,
					note: "登录成功",
					user_id: userid,
					create_nickname: user.nickname,
					create_ip: this.ip,
					create_time: create_time
				});
				user.user_id = userid;

				return await this.wxuser.where({
					openid: user.openid
				}).update({
					user_id: userid
				});
			});

			await this.session("user", user);

			return this.success();
		}
	}

	async indexAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			let user = await this.session("user");
			user.asset = await this.asset.where({
				user_id: user.user_id
			}).find();
			//定时21号结算上月收入
			let monthIncome = await this.order.getMonthIncome(user.user_id);
			user.this_income = monthIncome.this_income;
			user.last_income = monthIncome.last_income;
			user.this_balance_income = monthIncome.this_balance_income;
			user.last_balance_income = monthIncome.last_balance_income;
			let date = new Date();
			let nowTime = date.getTime();
			date.setDate(21);
			date.setHours(0, 0, 0, 0);
			let balanceTime = date.getTime();
			if(nowTime < balanceTime) {
				user.asset.amount = (user.asset.amount - user.this_balance_income - user.last_balance_income).toFixed(2);
			} else {
				user.asset.amount = (user.asset.amount - user.this_balance_income).toFixed(2);
			}
			
			user.level = await think.model("sys_user_level").where({id: user.asset.level}).getField("name",true);

			console.log(user);
			return this.success(user);
		}
	}

	async attendAction() {

		const self = this;
		let time = (new Date()).setHours(0, 0, 0, 0);
		let user = await this.session("user");

		let attend = await this.score.where({
			type: 1,
			user_id: user.user_id,
			create_time: ['>', time]
		}).find();
		if(!think.isEmpty(attend)) {
			return this.fail("今日已签到");
		}
		const insertId = await this.wxuser.transaction(async() => {
			await self.asset.db(self.wxuser.db()).where({
				user_id: user.user_id
			}).increment('score');
			const score_balance = await self.asset.db(self.wxuser.db()).where({
				user_id: user.user_id
			}).getField('score', true);
			return await self.score.db(self.wxuser.db()).add({
				user_id: user.user_id,
				type: 1,
				create_time: new Date().valueOf(),
				score: 1,
				balance: score_balance,
				status: 1,
				change: 1,
				note: `签到：+1 分`
			});
		});

		if(insertId) {
			return this.success('签到成功，积分 +1！');
		} else {
			return this.fail('签到失败,请重试');
		}
	}

	async billAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			let posts = this.post();
			let user = await this.session("user");

			let map = {
				user_id: user.user_id
			};
			if(posts.index == 0) {
				map.change = 1;

			} else {
				map.change = -1;
			}

			let bill = await this.money.page(posts.pageNum, posts.pageSize).where(map).order({
				id: 'DESC'
			}).countSelect();
			console.log(bill);
			bill.moneyType = think.config("setup.moneyType");
			bill.moneyStatus = think.config("setup.moneyStatus");
			return this.success(bill);
		}

	}
	async orderAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			let posts = this.post();
			let user = await this.session("user");
			console.log(JSON.stringify(posts));
			let map = {};

			if(posts.index == 0) {
				map.user_id = user.user_id;

			}

			if(posts.index == 1) {
				let agencyId = await this.agency.where({
					user_id: user.user_id
				}).getField("id", true);
				if(think.isEmpty(agencyId)) {
					return this.success({
						data: []
					});
				}
				map.agency_id = agencyId;
			}

			let order = await this.order.page(posts.pageNum, posts.pageSize).where(map).order({
				id: 'DESC'
			}).countSelect();

			return this.success(order);
		}
	}

	async teamAction() {

		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			let posts = this.post();
			let user = await this.session("user");
			console.log(JSON.stringify(posts));
			let agencyId = await this.agency.where({
				user_id: user.user_id
			}).getField("id", true);
			if(think.isEmpty(agencyId)) {
				return this.success({
					data: []
				});
			}
			let team = await this.asset.alias("a").field("u.headimgurl,u.nickname,a.rebate").where({
				'a.agency_id': agencyId
			}).join("wx_user AS u ON a.user_id=u.user_id").page(posts.pageNum, posts.pageSize).order({
				rebate: 'DESC'
			}).countSelect();

			return this.success(team);
		}

	}

	async orderWaitAction() {
		let posts = this.post();
		let order = await this.order.where({
			user_id: null,
			order_status: ['IN', "3,12"]
		}).limit(10).order({
			create_time: 'DESC'
		}).select();
		let user = await this.session("user");
		let level = await this.user.where({
			id: user.user_id
		}).getField("level", true);
		let orderBuyerRate = await think.model("sys_user_level").where({
			id: level || 1
		}).getField("rebate_ratio", true);
		order.forEach((v, i) => {
			order[i].buyer_commission = (order[i].effect_prediction * orderBuyerRate).toFixed(2);
			order[i].order_sn = v.order_sn.slice(0, 5) + "******" + v.order_sn.slice(-5);
		});
		return this.success(order);

	}
	async bindOrderAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			let posts = this.post();
			let user = await this.session("user");

			let data = await this.order.bindOrders(posts.orderNo, user.user_id);

			if(data.errno == 0) {
				return this.success(data.errmsg);
			} else {
				return this.fail(data.errmsg);
			}

		}
	}

	async getcashAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {

			let posts = this.post();
			let user = await this.session("user");
			let asset = await this.asset.where({
				user_id: user.user_id
			}).find();

			//定时21号结算上月收入
			let monthIncome = await this.order.getMonthIncome(userid);

			let date = new Date();
			let nowTime = date.getTime();
			date.setDate(21);
			date.setHours(0, 0, 0, 0);
			let balanceTime = date.getTime();
			if(nowTime < balanceTime) {
				asset.amount = (asset.amount - monthIncome.this_balance_income - monthIncome.last_balance_income).toFixed(2);
			} else {
				asset.amount = (asset.amount - monthIncome.this_balance_income).toFixed(2);
			}

			//定时21号结算上月收入

			if(asset.amount < posts.amount) {
				return this.fail("余额不足");
			}
			let note = "提现：" + posts.amount + " 元";
			if(!think.isEmpty(posts.alipay)) {
				note += '， 支付宝账号：' + posts.alipay + " ";
			}
			if(!think.isEmpty(posts.weixin)) {
				note += '， 微信账号：' + posts.weixin;
			}
			let self = this;

			const insertId = await this.wxuser.transaction(async() => {
				await self.asset.db(self.wxuser.db()).where({
					user_id: user.user_id
				}).decrement('amount', posts.amount);
				const amount_balance = await self.asset.db(self.wxuser.db()).where({
					user_id: user.user_id
				}).getField('amount', true);
				return await self.money.db(self.wxuser.db()).add({
					type: 2,
					create_time: new Date().valueOf(),
					amount: posts.amount,
					balance: amount_balance,
					status: 0,
					change: -1,
					user_id: user.user_id,
					note: note
				});
			});
			const email = this.service("email");
			await email.send({
				to: think.config("setup.adminEmail"),
				title: '提现通知',
				html: `${user.nickname}发起提现${posts.amount}元,微信号:${posts.weixin},请及时处理!`

			});

			if(insertId) {
				return this.success("提现请求已提交");
			} else {
				return this.fail('提现失败，请重试!');
			}

		}
	}

	async messageAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			let posts = this.post();
			let user = await this.session("user");
			let message = await this.message.page(posts.pageNum, posts.pageSize).where({
				user_id: user.user_id
			}).order({
				id: 'DESC'
			}).countSelect();

			return this.success(message);
		}
	}

	async shareAction() {
		if(this.isGet) {
			return this.appDisplay();
		}

		if(this.isPost) {
			let posts = this.post();
			let user = await this.session("user");

			let qrcode = await this.qrcode.where({
				user_id: user.user_id
			}).find();
			if(think.isEmpty(qrcode)) {
				let qrcodeId = await this.qrcode.add({
					user_id: user.user_id,
					share_num: 0,
					type: 1,
					create_time: new Date().valueOf()
				});
				const weixin = await this.conf.where({
					appid: this.appid
				}).find();
				let api = await this.wechatApi(weixin.id);
				let ticket = await api.createLimitQRCode(qrcodeId);
				let qrurl = await api.showQRCodeURL(ticket.ticket);
				await this.qrcode.where({
					id: qrcodeId
				}).update({
					qrcode_url: qrurl
				});

				return this.success({
					qrcode: qrurl,
					qrcode_id: qrcodeId
				});
			} else {
				return this.success({
					qrcode: qrcode.qrcode_url,
					qrcode_id: qrcode.id
				});
			}
		}
	}

	async wxsignAction() {

		let posts = this.post();
		const weixin = await this.conf.where({
			appid: this.appid
		}).find();
		let api = await this.wechatApi(weixin.id);
		let ticket = await api.getTicket();
		console.log(ticket);
		const wxsign = this.service("sign");
		let ret = wxsign.sign(ticket.ticket, posts.url);
		ret.appid = weixin.appid;
		return this.success(ret);

	}

	async helpAction() {
		return this.appDisplay();
	}
};